/*
 * loadFile.c
 *
 * Opens the passed file and loads it to memory.
 *
 * Return: Size of the file read.
 */

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "header/loadFile.h"

int loadToMem(const char *filename, char **result) 
{
    size_t allocated = MAX_LINE_LENGTH, len = MAX_LINE_LENGTH;
    char *p;    /* Pointer to allocated memory */
    char *walk; /* Aux. variable to leave out characters already read */
    int size = 0;
    size_t to_read;
    FILE *fp;

    to_read = len;
    
    /* Try to open the file */
    fp = fopen(filename, "rb");
    if (fp == NULL) {                
        return -1;          /* -1 means file opening fail  */
    } 

    p = malloc(allocated * sizeof(char));
    if(p == NULL) {
        fprintf(stderr, "Speicherreservierung fehlgeschlagen!");
        return -1;
    }
    
    walk = p;

    do {
        if (fgets(walk, to_read, fp) == NULL) {
            break;
        }

        to_read = strlen(p);
        allocated *= 2;
        
        p = realloc(p, allocated);
        if(p == NULL) {
            free(p);
            fprintf(stderr, "Speicherreservierung fehlgeschlagen!");
            return -1;
        }
        walk = p + to_read;
    } while(!feof(fp));

    walk = NULL;

    fseek(fp, 0, SEEK_END); 
    size = ftell(fp);

    fclose(fp);

    *result = p;    /* Set out parameter "result" */
    return size;
}